/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.mfpms.controller;

import com.xiaoleilu.hutool.StrUtil;
import com.xnck.mfpms.annotation.AuthenPassport;
import com.xnck.mfpms.annotation.NeedMenu;
import com.xnck.mfpms.constant.ContextConstant;
import com.xnck.mfpms.service.AccountService;
import com.xnck.mfpms.util.SessionUtils;
import com.xnck.mfpms.util.ValidatCodeUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/")
public class RootController extends BaseController{

    private static Logger log = Logger.getLogger(RootController.class);

    @Autowired
    private AccountService accountService;

    @NeedMenu
    @AuthenPassport
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView getIndex(){
        ModelAndView mv = new ModelAndView("/index");
        return mv;
    }

    @AuthenPassport
    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public ModelAndView getWelcome(){
        ModelAndView mv = new ModelAndView("/welcome");
        return mv;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView getLogin(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "f", required = false) String flag,
                                 @RequestParam(value = "url", required = false) String returnUrl){
        ModelAndView mv = new ModelAndView("/login");
        String alertMessage = this.getAlertMessage(flag);
        mv.addObject("alertMessage", alertMessage);
        this.setLoginReturnUrl(mv, returnUrl);
        return mv;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView postLogin(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "uname") String userName,
                                  @RequestParam(value = "pwd") String passWord,
                                  @RequestParam(value = "vcode") String validatCode,
                                  @RequestParam(value = "url", required = false) String returnUrl) {
        boolean isSetIdentity = false;
        boolean isTrueCode = this.checkValidatCode(request, validatCode);
        if (isTrueCode){
            //获得当前登录人的凭证信息
            String curUserId;
            try {
                curUserId = accountService.login(userName, passWord);
            }
            catch (Exception e){
                log.error(e.toString());
                curUserId = null;
            }
            //如果凭证信息正确，则记录凭证
            boolean isLogin = StrUtil.isNotBlank(curUserId);
            if (isLogin) {
                isSetIdentity = this.setIdentitySession(request, curUserId);
            }
        }
        //如果凭证已经记录，则进行视图处理
        if (isSetIdentity){
            this.redirectUrl(request, response, returnUrl);
            return null;
        }
        else {
            ModelAndView mv = new ModelAndView("/login");
            String alertMessage = this.getAlertMessage(ContextConstant.VALUE_AUTHEN_FAILED);
            mv.addObject("alertMessage", alertMessage);
            this.setLoginReturnUrl(mv, returnUrl);
            mv.addObject("uname", userName);
            return mv;
        }
    }

    /**
     * 注销
     * @param request
     * @param response
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public void getLogout(HttpServletRequest request, HttpServletResponse response){
        try {
            SessionUtils.removeAttr(request, ContextConstant.IDEN_CERT_KEY);
        } catch (Exception e){
            log.error(e.toString());
        }
        this.redirectUrl(request, response, null);
    }

    /**
     * 验证码
     * @param request
     * @param response
     */
    @RequestMapping(value = "/vcode", method = RequestMethod.GET)
    public void getValidatCode(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        long time = System.currentTimeMillis();
        response.setDateHeader("Last-Modified", time);
        response.setDateHeader("Date", time);
        response.setDateHeader("Expires", time);
        try {
            String validatCode = ValidatCodeUtils.create(response.getOutputStream());
            SessionUtils.setAttr(request, ContextConstant.VALIDAT_CODE_KEY, validatCode.toLowerCase());
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /**
     * 获得提示信息
     * @param flag
     * @return
     */
    private String getAlertMessage(String flag){
        if (ContextConstant.VALUE_SESSION_OUT.equals(flag)){
            return "请重新登录";
        }
        else if (ContextConstant.VALUE_AUTHEN_FAILED.equals(flag)){
            return "请输入正确的用户名、密码和验证码";
        }
        else {
            return null;
        }
    }

    /**
     * 设置登录页的ReturnUrl
     * @param mv
     * @param returnUrl
     */
    private void setLoginReturnUrl(ModelAndView mv, String returnUrl){
        if (StrUtil.isNotBlank(returnUrl)){
            try {
                mv.addObject("returnUrl", URLEncoder.encode(returnUrl, "utf-8"));
            }
            catch (Exception e){
                log.error(e.toString());
            }
        }
    }

    /**
     * 写入身份凭证
     * @param request
     * @param curUserId
     * @return
     */
    private boolean setIdentitySession(HttpServletRequest request, String curUserId){
        try {
            SessionUtils.setCurrentUserId(request, curUserId);
            return true;
        }
        catch (Exception e){
            log.error(e.toString());
            return false;
        }
    }

    /**
     * URL跳转
     * @param request
     * @param response
     * @param returnUrl
     */
    private void redirectUrl(HttpServletRequest request, HttpServletResponse response, String returnUrl){
        try {
            if (StrUtil.isBlank(returnUrl)){
                response.sendRedirect(request.getContextPath());
            }
            else {
                response.sendRedirect(returnUrl);
            }
        }
        catch (Exception e){
            log.error(e.toString());
        }
    }

    /**
     * 检查验证码是否与Session中存储的相同
     * @param request
     * @param validatCode
     * @return
     */
    private boolean checkValidatCode(HttpServletRequest request, String validatCode){
        String sessionCode = null;
        try {
            sessionCode = SessionUtils.getAttr(request, ContextConstant.VALIDAT_CODE_KEY).toString();
        }
        catch (Exception e){
            log.error(e.toString());
        }
        if (StrUtil.isNotBlank(sessionCode) && sessionCode.toLowerCase().equals(validatCode)){
            return true;
        }
        else {
            return false;
        }
    }
}
